﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Model
{
    public class ActivityService
    {
        /// <summary>
        /// 创建活动
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        public ServiceResult<Activity> Create(int accountId,
            string title,
            string categoryCode,
            string address,
            string city,
            double longitude,
            double latitude,
            DateTime beginTime,
            DateTime endTime,
            int maxPersonCount,
            decimal costPrePerson,
            string description,
            List<Guid> images,
            List<int> inviteFriends)
        {
            if (string.IsNullOrEmpty(title)
                || maxPersonCount <= 0)
            {
                return new ServiceResult<Activity>(ErrorCode.Common_InvalidParameter);
            }
            if (endTime <= beginTime)
            {
                return new ServiceResult<Activity>(ErrorCode.CreateActivity_InvalidTime);
            }
            if (beginTime <= DateTime.Now
                || endTime <= DateTime.Now)
            {
                return new ServiceResult<Activity>(ErrorCode.CreateActivity_InvalidTime);
            }

            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                AccountRepository aRep = new AccountRepository(dbContext);
                ActivityRepository activityReps = new ActivityRepository(dbContext);
                ActivityMemberRepository amRep = new ActivityMemberRepository(dbContext);
                MessageRepository msgReps = new MessageRepository(dbContext);
                MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);

                Account creator = aRep.Get(accountId);

                Activity activity = new Activity();
                activity.Id = Guid.NewGuid();
                activity.CreatorId = accountId;
                activity.CreatedTime = DateTime.Now;
                activity.CurrentPersonCount = 0;
                activity.IsFinished = false;

                activity.Title = title;
                activity.Address = address;
                activity.CategoryCode = categoryCode;
                activity.BeginTime = beginTime;
                activity.EndTime = endTime;
                activity.MaxPersonCount = maxPersonCount;
                activity.CostPrePerson = costPrePerson;
                activity.Descritpion = description;

                activity.City = city;
                activity.Longitude = longitude;
                activity.Latitude = latitude;

                activityReps.Create(activity);

                //// 创建人加入到活动中
                //ActivityMember memberOfCreator = new ActivityMember();
                //memberOfCreator.Id = Guid.NewGuid();
                //memberOfCreator.ActivityId = activity.Id;
                //memberOfCreator.Type = BasicData.ActivityMemberType.Creator;
                //memberOfCreator.JoinTime = activity.CreatedTime;
                //memberOfCreator.UserId = accountId;
                //amRep.Create(memberOfCreator);

                // 关联图片
                if (images != null)
                {
                    for (int index = 0; index < images.Count; index++)
                    {
                        ActivityImage image = new ActivityImage();
                        image.Id = Guid.NewGuid();
                        image.ActivityId = activity.Id;
                        image.ImageId = images[index];
                        image.Order = index;
                        activityReps.SaveImage(image);
                    }
                }

                // 向好友发送邀请消息
                if (inviteFriends != null)
                {
                    for (int index = 0; index < inviteFriends.Count; index++)
                    {
                        // 生成系统消息
                        Message sysMessage = new Message();
                        sysMessage.Id = Guid.NewGuid();
                        sysMessage.Type = BasicData.MessageType.ActivityInvitation;
                        sysMessage.ReceiverId = inviteFriends[index];
                        sysMessage.SenderId = accountId;
                        sysMessage.Title = "活动邀请";
                        sysMessage.Content = string.Format("{0}邀请您加入活动[{1}]!", creator.NickName, activity.Title);
                        sysMessage.CreatedTime = DateTime.Now;

                        // 生成MessageSet
                        MessageClip messageSet = new MessageClip();
                        messageSet.Id = Guid.NewGuid();
                        messageSet.IdentityText = string.Format("ACT_INVITE{0}-{1}", activity.Id, inviteFriends[index]);
                        messageSet.Type = BasicData.MessageClipType.SystemNotice;
                        messageSet.MessageType = BasicData.MessageType.ActivityInvitation;
                        messageSet.ReceiverId = sysMessage.ReceiverId;
                        messageSet.MessageCount = 1;
                        messageSet.NewMessageCount = 1;
                        messageSet.CreatedTime = sysMessage.CreatedTime;
                        messageSet.LastestSenderId = sysMessage.SenderId;
                        messageSet.LastestContent = sysMessage.Content;
                        messageSet.LastestTitle = sysMessage.Title;
                        messageSet.LastestUpdatedTime = sysMessage.CreatedTime;
                        messageSet.Tag = activity.Id.ToString();

                        sysMessage.MessageClipId = messageSet.Id;

                        msgSetReps.Create(messageSet);
                        msgReps.Create(sysMessage);
                    }
                }

                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<Activity>(ErrorCode.NoError, activity);
                }
                return new ServiceResult<Activity>(ErrorCode.DB_Error);
            }
        }

        public ServiceResult<PagedList<Activity>> GetDefaultActivityList(string city,
            double longitude,
            double latitude,
            int start,
            int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                List<Activity> list = reps.GetDefaultActivityList(city, longitude, latitude, start, limit);

                PagedList<Activity> pagedList = new PagedList<Activity>();
                pagedList.Start = start;
                pagedList.Limit = limit;
                pagedList.Items.AddRange(list);
                pagedList.Total = reps.GetDefaultActivityCount(city, longitude, latitude);
                return new ServiceResult<PagedList<Activity>>(ErrorCode.NoError, pagedList);
            }
        }

        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="city"></param>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <param name="categoryCode"></param>
        /// <param name="timeCondition"></param>
        /// <param name="distanceCondition"></param>
        /// <param name="personCondition"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ServiceResult<PagedList<Activity>> GetActivityList(string city,
            double longitude,
            double latitude,
            string categoryCode,
            int timeCondition,
            int distanceCondition,
            int personCondition,
            int page,
            int limit)
        {
            if (limit > 25)
            {
                limit = 25;
            }

            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                List<Activity> list = reps.GetActivityListByCategory(city, longitude, latitude, categoryCode, page, limit);

                PagedList<Activity> pagedList = new PagedList<Activity>();
                pagedList.Items.AddRange(list);
                pagedList.Start = page * limit;
                pagedList.Limit = limit;
                pagedList.Total = reps.GetActivityCountByCategory(city, longitude, latitude, categoryCode);

                return new ServiceResult<PagedList<Activity>>(ErrorCode.NoError, pagedList);
            }
        }

        public ServiceResult<PagedList<Activity>> GetUnfinishedActivityList4User(int userId, int start, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                List<Activity> list = reps.GetUnfinishedActivityList4User(userId, start, limit);

                PagedList<Activity> pagedList = new PagedList<Activity>();
                pagedList.Start = start;
                pagedList.Limit = limit;
                pagedList.Total = reps.GetUnfinishedActivityCount4User(userId);
                pagedList.Items.AddRange(list);

                return new ServiceResult<PagedList<Activity>>(ErrorCode.NoError, pagedList);
            }
        }

        public ServiceResult<int> GetUnfinishedActivityCount4User(int userId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                int count = reps.GetUnfinishedActivityCount4User(userId);

                return new ServiceResult<int>(ErrorCode.NoError, count);
            }
        }

        /// <summary>
        /// 获取创建者创建的未完成的活动
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ServiceResult<PagedList<Activity>> GetUnfinishedActivityList4Creator(int userId, int start, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                List<Activity> list = reps.GetUnfinishedActivityList4Creator(userId, start, limit);

                PagedList<Activity> pagedList = new PagedList<Activity>();
                pagedList.Start = start;
                pagedList.Limit = limit;
                pagedList.Total = reps.GetUnfinishedActivityCount4Creator(userId);
                pagedList.Items.AddRange(list);
                return new ServiceResult<PagedList<Activity>>(ErrorCode.NoError, pagedList);
            }
        }

        /// <summary>
        /// 获取创建者创建的未完成的活动
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ServiceResult<int> GetUnfinishedActivityCount4Creator(int userId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                int count = reps.GetUnfinishedActivityCount4Creator(userId);
                return new ServiceResult<int>(ErrorCode.NoError, count);
            }
        }

        public ServiceResult<PagedList<Activity>> GetFinishedActivityList4User(int userId, int start, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                List<Activity> list = reps.GetFinishedActivityList4User(userId, start, limit);
                PagedList<Activity> pagedList = new PagedList<Activity>();
                pagedList.Start = start;
                pagedList.Limit = limit;
                pagedList.Total = reps.GetFinishedActivityCount4User(userId);
                pagedList.Items.AddRange(list);
                return new ServiceResult<PagedList<Activity>>(ErrorCode.NoError, pagedList);
            }
        }

        public ServiceResult<int> GetFinishedActivityCount4User(int userId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);

                int count = reps.GetFinishedActivityCount4User(userId);
                return new ServiceResult<int>(ErrorCode.NoError, count);
            }
        }

        public ServiceResult<List<ImageResource>> GetActivityImageList(Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityImageRepository reps = new ActivityImageRepository(dbContext);
                List<ImageResource> lst = reps.GetImages(activityId);
                return new ServiceResult<List<ImageResource>>(ErrorCode.NoError, lst);
            }
        }

        public ServiceResult<ActivityDetail> GetActivity(Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);
                AccountRepository accountReps = new AccountRepository(dbContext);
                BaseDataRepository bdReps = new BaseDataRepository(dbContext);

                Activity activity = reps.Get(activityId);
                BaseDataItem baseDataItem = bdReps.GetItem(BasicData.BD_ActivityCategory, activity.CategoryCode);
                Account creator = accountReps.Get(activity.CreatorId);

                ActivityDetail detail = new ActivityDetail();
                detail.Id = activity.Id;
                detail.Title = activity.Title;
                detail.CategoryCode = activity.CategoryCode;
                detail.CategoryCaption = baseDataItem.Caption;
                detail.Address = activity.Address;
                detail.BeginTime = activity.BeginTime;
                detail.EndTime = activity.EndTime;
                detail.City = activity.City;
                detail.CostPrePerson = activity.CostPrePerson;
                detail.CreatedTime = activity.CreatedTime;
                detail.CreatorId = activity.CreatorId;
                detail.CreatorName = creator.Name;
                detail.CreatorPhone = creator.Phone;
                detail.CreatorNickName = creator.NickName;
                detail.CreatorAvatarUrl = creator.AvatarUrl;
                detail.CurrentPersonCount = activity.CurrentPersonCount;
                detail.Descritpion = activity.Descritpion;
                detail.IsFinished = activity.IsFinished;
                detail.Latitude = activity.Latitude;
                detail.Longitude = activity.Longitude;
                detail.MaxPersonCount = activity.MaxPersonCount;

                return new ServiceResult<ActivityDetail>(ErrorCode.NoError, detail);
            }
        }

        /// <summary>
        /// 发布活动反馈
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        /// <param name="content"></param>
        public ServiceResult<ActivityFeedback> Feedback(int userId, Guid activityId, string content)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository acReps = new ActivityRepository(dbContext);

                ActivityMemberRepository amReps = new ActivityMemberRepository(dbContext);

                Activity activity = acReps.Get(activityId);
                if (activity == null)
                {
                    // 活动不存在
                    return new ServiceResult<ActivityFeedback>(ErrorCode.ActivityFeedback_NotExist);
                }
                else if (activity.IsFinished == false)
                {
                    // 活动还未结束
                    return new ServiceResult<ActivityFeedback>(ErrorCode.ActivityFeedback_NotFinished);
                }

                ActivityMember member = amReps.Get(activityId, userId);
                if (member == null && activity.CreatorId != userId)
                {
                    // 没有参加此活动
                    return new ServiceResult<ActivityFeedback>(ErrorCode.ActivityFeedback_NotJoined);
                }
                ActivityFeedbackRepository fbReps = new ActivityFeedbackRepository(dbContext);

                ActivityFeedback feedback = new ActivityFeedback();
                feedback.Id = Guid.NewGuid();
                feedback.CreatorId = userId;
                feedback.CreatedTime = DateTime.Now;
                feedback.Content = content;
                feedback.ActivityId = activityId;

                fbReps.Create(feedback);

                MessageRepository reps = new MessageRepository(dbContext);
                MessageClipRepository mcReps = new MessageClipRepository(dbContext);
                // 生成消息
                List<Data.ActivityMember> memberList = amReps.GetList(activityId);

                bool creatorIsMember = false;
                for (int index = 0; index < memberList.Count; index++)
                {
                    int targetUserId = memberList[index].Id;

                    if (targetUserId == activity.CreatorId)
                    {
                        creatorIsMember = true;
                    }

                    DateTime now = DateTime.Now;
                    string targetClipIdentityText = string.Format("ACT_FB{0}-{1}", activityId, targetUserId);

                    // 获取目标消息夹
                    MessageClip targetMessageClip = mcReps.Get(BasicData.MessageClipType.ActivityFeedback, targetClipIdentityText);
                    if (targetMessageClip == null)
                    {
                        targetMessageClip = new MessageClip();
                        targetMessageClip.Id = Guid.NewGuid();
                        targetMessageClip.CreatedTime = now;
                        targetMessageClip.ReceiverId = targetUserId;
                        targetMessageClip.MessageCount = 1;
                        targetMessageClip.NewMessageCount = 1;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;

                        targetMessageClip.Type = BasicData.MessageClipType.ActivityFeedback;
                        targetMessageClip.MessageType = BasicData.MessageType.ActivityFeedback;
                        targetMessageClip.IdentityText = targetClipIdentityText;

                        targetMessageClip.Tag = activityId.ToString();

                        mcReps.Create(targetMessageClip);
                    }
                    else
                    {
                        targetMessageClip.MessageCount++;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;
                        targetMessageClip.IsDeleted = false;
                        mcReps.Update(targetMessageClip);
                    }
                    // 创建消息
                    Message targetMessage = new Message();
                    targetMessage.Id = Guid.NewGuid();
                    targetMessage.SenderId = userId;
                    targetMessage.ReceiverId = targetUserId;
                    targetMessage.Content = content;
                    targetMessage.CreatedTime = now;
                    targetMessage.Type = BasicData.MessageType.ActivityFeedback;
                    targetMessage.MessageClipId = targetMessageClip.Id;
                    reps.Create(targetMessage);
                }

                if (!creatorIsMember)
                {
                    // 队长不是成员，单独给队长发送一份
                    int targetUserId = activity.CreatorId;

                    DateTime now = DateTime.Now;
                    string targetClipIdentityText = string.Format("ACT_FB{0}-{1}", activityId, targetUserId);

                    // 获取目标消息夹
                    MessageClip targetMessageClip = mcReps.Get(BasicData.MessageClipType.ActivityFeedback, targetClipIdentityText);
                    if (targetMessageClip == null)
                    {
                        targetMessageClip = new MessageClip();
                        targetMessageClip.Id = Guid.NewGuid();
                        targetMessageClip.CreatedTime = now;
                        targetMessageClip.ReceiverId = targetUserId;
                        targetMessageClip.MessageCount = 1;
                        targetMessageClip.NewMessageCount = 1;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;

                        targetMessageClip.Type = BasicData.MessageClipType.ActivityFeedback;
                        targetMessageClip.MessageType = BasicData.MessageType.ActivityFeedback;
                        targetMessageClip.IdentityText = targetClipIdentityText;

                        targetMessageClip.Tag = activityId.ToString();

                        mcReps.Create(targetMessageClip);
                    }
                    else
                    {
                        targetMessageClip.MessageCount++;
                        targetMessageClip.LastestContent = content;
                        targetMessageClip.LastestSenderId = userId;
                        targetMessageClip.LastestTitle = activity.Title;
                        targetMessageClip.LastestUpdatedTime = now;
                        targetMessageClip.IsDeleted = false;
                        mcReps.Update(targetMessageClip);
                    }
                    // 创建消息
                    Message targetMessage = new Message();
                    targetMessage.Id = Guid.NewGuid();
                    targetMessage.SenderId = userId;
                    targetMessage.ReceiverId = targetUserId;
                    targetMessage.Content = content;
                    targetMessage.CreatedTime = now;
                    targetMessage.Type = BasicData.MessageType.ActivityFeedback;
                    targetMessage.MessageClipId = targetMessageClip.Id;
                    reps.Create(targetMessage);
                }

                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<ActivityFeedback>(ErrorCode.NoError, feedback);
                }
                return new ServiceResult<ActivityFeedback>(ErrorCode.DB_Error);
            }
        }

        /// <summary>
        /// 获取反馈列表
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public ServiceResult<List<Data.ActivityFeedbackView>> GetFeedbackList(Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityFeedbackRepository reps = new ActivityFeedbackRepository(dbContext);

                List<Data.ActivityFeedbackView> lst = reps.Get(activityId);

                return new ServiceResult<List<Data.ActivityFeedbackView>>(ErrorCode.NoError, lst);
            }
        }

        /// <summary>
        /// 加入活动
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        public ServiceResult<string> Join(int userId, Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                AccountRepository userReps = new AccountRepository(dbContext);
                ActivityRepository acReps = new ActivityRepository(dbContext);
                ActivityMemberRepository amReps = new ActivityMemberRepository(dbContext);
                MessageClipRepository mcReps = new MessageClipRepository(dbContext);
                MessageRepository mReps = new MessageRepository(dbContext);
                ActivityJoinRequestRepository ajrReps = new ActivityJoinRequestRepository(dbContext);
                

                ActivityMember existMember = amReps.Get(activityId, userId);
                if (existMember != null)
                {
                    // 已经加入此活动了
                    return new ServiceResult<string>(ErrorCode.JoinActivity_HasJoined);
                }

                Account user = userReps.Get(userId);
                if (user == null)
                {
                    // 用户不存在
                    return new ServiceResult<string>(ErrorCode.JoinActivity_UserNotExist);
                }

                Activity activity = acReps.Get(activityId);
                if (activity == null)
                {
                    // 活动不存在
                    return new ServiceResult<string>(ErrorCode.JoinActivity_ActivityNotExist);
                }
                else if (activity.IsFinished == true)
                {
                    // 活动已结束
                    return new ServiceResult<string>(ErrorCode.JoinActivity_ActivityHasFinished);
                }
                else if (activity.CurrentPersonCount == activity.MaxPersonCount)
                {
                    // 活动人数已满
                    return new ServiceResult<string>(ErrorCode.JoinActivity_HasFull);
                }

                MessageClip inviteMessage = mcReps.Get(BasicData.MessageClipType.SystemNotice, string.Format("ACT_INVITE{0}-{1}", activityId, userId));
                if (inviteMessage == null)
                {
                    ActivityJoinRequest request = ajrReps.Get(activityId, userId);
                    if (request != null)
                    {
                        return new ServiceResult<string>(ErrorCode.JoinActivity_HasRequest);
                    }
                    request = new ActivityJoinRequest();
                    request.ActivityId = activityId;
                    request.UserId = userId;
                    request.CreatedTime = DateTime.Now;
                    ajrReps.Create(request);

                    MessageRepository msgReps = new MessageRepository(dbContext);
                    MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);

                    // 获取消息夹，可能这个人之前申请被否决了
                    string messageClipIdentity = string.Format("ACT_JR{0}-{1}", activity.Id, userId);
                    // 没有收到好友邀请，发送加入请求给队长
                    Message sysMessage = new Message();
                    sysMessage.Id = Guid.NewGuid();
                    sysMessage.Type = BasicData.MessageType.JoinActivityRequest;
                    sysMessage.ReceiverId = activity.CreatorId;
                    sysMessage.SenderId = userId;
                    sysMessage.Title = "申请加入活动";
                    sysMessage.Content = string.Format("{0}申请加入活动[{1}]!", user.NickName, activity.Title);
                    sysMessage.CreatedTime = DateTime.Now;
                    
                    MessageClip messageSet = msgSetReps.Get(BasicData.MessageClipType.SystemNotice, messageClipIdentity);
                    if(messageSet !=null)
                    {
                        messageSet.IsDeleted = false;
                        messageSet.MessageCount++;

                        msgSetReps.Update(messageSet);
                    }
                    else
                    {
                        // 生成MessageSet
                        messageSet = new MessageClip();
                        messageSet.Id = Guid.NewGuid();
                        messageSet.IdentityText = messageClipIdentity;
                        messageSet.Type = BasicData.MessageClipType.SystemNotice;
                        messageSet.MessageType = BasicData.MessageType.JoinActivityRequest;
                        messageSet.ReceiverId = activity.CreatorId;
                        messageSet.MessageCount = 1;
                        messageSet.CreatedTime = sysMessage.CreatedTime;
                        messageSet.IsDeleted = false;
                        messageSet.Tag = activity.Id.ToString();
                        msgSetReps.Create(messageSet);
                    }
                    messageSet.NewMessageCount = 1;
                    messageSet.LastestSenderId = sysMessage.SenderId;
                    messageSet.LastestContent = sysMessage.Content;
                    messageSet.LastestTitle = sysMessage.Title;
                    messageSet.LastestUpdatedTime = sysMessage.CreatedTime;

                    sysMessage.MessageClipId = messageSet.Id;

                    msgReps.Create(sysMessage);
                }
                else
                {
                    // 具有好友邀请，直接加入活动
                    ActivityMember member = new ActivityMember();
                    member.Id = Guid.NewGuid();
                    member.ActivityId = activityId;
                    member.UserId = userId;
                    member.JoinTime = DateTime.Now;
                    member.Type = BasicData.ActivityMemberType.Member;

                    amReps.Create(member);

                    // 更新活动的当前人数
                    activity.CurrentPersonCount++;
                    acReps.Update(activity.Id, activity);


                    // 如果有邀请消息夹，删除邀请消息夹
                    new MessageService().DeleteMessageClip(dbContext, BasicData.MessageClipType.SystemNotice, string.Format("ACT_INVITE{0}-{1}", activityId, userId));
                }
                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<string>(ErrorCode.NoError, string.Empty);
                }
                return new ServiceResult<string>(ErrorCode.DB_Error);
            }
        }

        public ServiceResult<ActivityMember> AcceptJoinRequest(int userId, Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityMemberRepository amRep = new ActivityMemberRepository(dbContext);
                ActivityRepository aReps = new ActivityRepository(dbContext);
                ActivityJoinRequestRepository ajrRep = new ActivityJoinRequestRepository(dbContext);
                ActivityJoinRequest request = ajrRep.Get(activityId, userId);

                if (request == null)
                {
                    return new ServiceResult<ActivityMember>(ErrorCode.AuditingActivityJoinRequest_NoRequest);
                }

                // 删除request
                ajrRep.Delete(request);

                Activity activity = aReps.Get(activityId);

                ActivityMember member = new ActivityMember();
                member.Id = Guid.NewGuid();
                member.ActivityId = activityId;
                member.UserId = userId;
                member.JoinTime = DateTime.Now;
                member.Type = BasicData.ActivityMemberType.Member;

                amRep.Create(member);

                // 更新活动的当前人数
                activity.CurrentPersonCount++;
                aReps.Update(activity.Id, activity);

                // 删除队长收到的申请消息
                new MessageService().DeleteMessageClip(dbContext, BasicData.MessageClipType.SystemNotice, string.Format("ACT_JR{0}-{1}", activityId, userId));
                // 发送申请通过的消息

                MessageRepository msgReps = new MessageRepository(dbContext);
                MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);

                // 没有收到好友邀请，发送加入请求给队长
                Message sysMessage = new Message();
                sysMessage.Id = Guid.NewGuid();
                sysMessage.Type = BasicData.MessageType.JoinActivitySuccess;
                sysMessage.ReceiverId = userId;
                sysMessage.SenderId = activity.CreatorId;
                sysMessage.Title = "活动申请已通过";
                sysMessage.Content = string.Format("您已经成功加入活动[{0}]!", activity.Title);
                sysMessage.CreatedTime = DateTime.Now;

                // 生成MessageSet
                MessageClip messageSet = new MessageClip();
                messageSet.Id = Guid.NewGuid();
                messageSet.IdentityText = string.Format("Act_JR_SUCCESS{0}-{1}", activity.Id, userId);
                messageSet.Type = BasicData.MessageClipType.SystemNotice;
                messageSet.MessageType = BasicData.MessageType.JoinActivitySuccess;
                messageSet.ReceiverId = userId;
                messageSet.MessageCount = 1;
                messageSet.NewMessageCount = 1;
                messageSet.CreatedTime = sysMessage.CreatedTime;
                messageSet.LastestSenderId = sysMessage.SenderId;
                messageSet.LastestContent = sysMessage.Content;
                messageSet.LastestTitle = sysMessage.Title;
                messageSet.LastestUpdatedTime = sysMessage.CreatedTime;
                messageSet.Tag = activity.Id.ToString();

                sysMessage.MessageClipId = messageSet.Id;

                msgSetReps.Create(messageSet);
                msgReps.Create(sysMessage);

                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<ActivityMember>(ErrorCode.NoError, member);
                }
                return new ServiceResult<ActivityMember>(ErrorCode.DB_Error);
            }
        }

        /// <summary>
        /// 不同意活动申请
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public ServiceResult<string> RejectJoinRequest(int userId, Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityMemberRepository amRep = new ActivityMemberRepository(dbContext);
                ActivityRepository aReps = new ActivityRepository(dbContext);
                ActivityJoinRequestRepository ajrRep = new ActivityJoinRequestRepository(dbContext);
                ActivityJoinRequest request = ajrRep.Get(activityId, userId);

                if (request == null)
                {
                    return new ServiceResult<string>(ErrorCode.AuditingActivityJoinRequest_NoRequest);
                }

                // 删除request
                ajrRep.Delete(request);

                Activity activity = aReps.Get(activityId);

                // 删除队长收到的申请消息
                new MessageService().DeleteMessageClip(dbContext, BasicData.MessageClipType.SystemNotice, string.Format("ACT_JR{0}-{1}", activityId, userId));

                // 发送申请不通过的消息
                MessageRepository msgReps = new MessageRepository(dbContext);
                MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);

                // 没有收到好友邀请，发送加入请求给队长
                Message sysMessage = new Message();
                sysMessage.Id = Guid.NewGuid();
                sysMessage.Type = BasicData.MessageType.JoinActivityFailure;
                sysMessage.ReceiverId = userId;
                sysMessage.SenderId = activity.CreatorId;
                sysMessage.Title = "活动申请被拒绝";
                sysMessage.Content = string.Format("您申请加入活动[{0}]，但是被拒绝!", activity.Title);
                sysMessage.CreatedTime = DateTime.Now;

                // 生成MessageSet
                MessageClip messageSet = new MessageClip();
                messageSet.Id = Guid.NewGuid();
                messageSet.IdentityText = string.Format("Act_JR_FAILURE{0}-{1}", activity.Id, userId);
                messageSet.Type = BasicData.MessageClipType.SystemNotice;
                messageSet.MessageType = BasicData.MessageType.JoinActivityFailure;
                messageSet.ReceiverId = userId;
                messageSet.MessageCount = 1;
                messageSet.NewMessageCount = 1;
                messageSet.CreatedTime = sysMessage.CreatedTime;
                messageSet.LastestSenderId = sysMessage.SenderId;
                messageSet.LastestContent = sysMessage.Content;
                messageSet.LastestTitle = sysMessage.Title;
                messageSet.LastestUpdatedTime = sysMessage.CreatedTime;
                messageSet.Tag = activity.Id.ToString();

                sysMessage.MessageClipId = messageSet.Id;

                msgSetReps.Create(messageSet);
                msgReps.Create(sysMessage);

                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<string>(ErrorCode.NoError, string.Empty);
                }
                return new ServiceResult<string>(ErrorCode.DB_Error);
            }
        }

        /// <summary>
        /// 退出活动
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        public ServiceResult<ActivityMember> Leave(int userId, Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                AccountRepository userReps = new AccountRepository(dbContext);
                ActivityRepository acReps = new ActivityRepository(dbContext);

                Account user = userReps.Get(userId);
                if (user == null)
                {
                    // 用户不存在
                    return new ServiceResult<ActivityMember>(ErrorCode.LeaveActivity_UserNotExist);
                }
                Activity activity = acReps.Get(activityId);
                if (activity == null)
                {
                    // 活动不存在
                    return new ServiceResult<ActivityMember>(ErrorCode.LeaveActivity_ActivityNotExist);
                }

                // 如果有邀请消息夹，删除邀请消息夹
                new MessageService().DeleteMessageClip(dbContext, BasicData.MessageClipType.SystemNotice, string.Format("ACT_INVITE{0}-{1}", activityId, userId));


                if (activity.IsFinished == true)
                {
                    // 活动已结束
                    return new ServiceResult<ActivityMember>(ErrorCode.LeaveActivity_ActivityHasFinished);
                }

                ActivityMemberRepository amReps = new ActivityMemberRepository(dbContext);

                ActivityMember member = amReps.Get(activityId, userId);
                if (member != null)
                {
                    amReps.Delete(member);

                    // 更新活动的当前人数
                    activity.CurrentPersonCount--;
                    acReps.Update(activity.Id, activity);

                    // 发送消息给队长，通知有人退出
                    MessageRepository msgReps = new MessageRepository(dbContext);
                    MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);

                    string identityText = string.Format("ACT_LEAVE{0}", activity.Id);

                    MessageClip messageSet = msgSetReps.Get(BasicData.MessageType.SystemNotice, identityText);

                    Message sysMessage = new Message();
                    sysMessage.Id = Guid.NewGuid();
                    sysMessage.Type = BasicData.MessageType.LeaveActivity;
                    sysMessage.ReceiverId = activity.CreatorId;
                    sysMessage.SenderId = userId;
                    sysMessage.Title = "退出活动通知";
                    sysMessage.Content = string.Format("{0}退出了活动{1}!", user.NickName, activity.Title);
                    sysMessage.CreatedTime = DateTime.Now;

                    // 生成MessageSet
                    if (messageSet != null)
                    {
                        messageSet.IsDeleted = false;
                        messageSet.MessageCount++;

                        msgSetReps.Update(messageSet);
                    }
                    else
                    {
                        messageSet = new MessageClip();
                        messageSet.Id = Guid.NewGuid();
                        messageSet.IdentityText = string.Format("ACT_LEAVE{0}", activity.Id);
                        messageSet.Type = BasicData.MessageClipType.SystemNotice;
                        messageSet.MessageType = BasicData.MessageType.LeaveActivity;
                        messageSet.ReceiverId = activity.CreatorId;
                        messageSet.MessageCount = 1;
                        messageSet.Tag = activity.Id.ToString();
                        messageSet.CreatedTime = sysMessage.CreatedTime;

                        msgSetReps.Create(messageSet);
                    }
                    messageSet.NewMessageCount = 1;
                    messageSet.LastestSenderId = sysMessage.SenderId;
                    messageSet.LastestContent = sysMessage.Content;
                    messageSet.LastestTitle = sysMessage.Title;
                    messageSet.LastestUpdatedTime = sysMessage.CreatedTime;

                    sysMessage.MessageClipId = messageSet.Id;
                    msgReps.Create(sysMessage);

                }
                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<ActivityMember>(ErrorCode.NoError, member);
                }
                return new ServiceResult<ActivityMember>(ErrorCode.DB_Error);
            }
        }

        /// <summary>
        /// 获取成员列表
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public ServiceResult<List<Data.ActivityMember>> GetMemberList(Guid activityId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityMemberRepository reps = new ActivityMemberRepository(dbContext);

                List<Data.ActivityMember> lst = reps.GetList(activityId);

                return new ServiceResult<List<Data.ActivityMember>>(ErrorCode.NoError, lst);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="categoryCode"></param>
        /// <param name="city"></param>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <param name="timeCondition">0:不限,1:最近发布,2:最远发布</param>
        /// <param name="distanceCondition">0:不限,1:离我最近,2:离我最远</param>
        /// <param name="personCountCondition">0:不限,1:未满人数最多,2:未满人数最少</param>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public ServiceResult<PagedList<Activity>> SearchActivityListByCategory(string filter, string categoryCode, string city,
            double longitude, double latitude, int timeCondition, int distanceCondition,
            int personCountCondition,
            int start, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);
                List<Activity> list = dbContext.Database.SqlQuery<Activity>("exec [SP_SearchActivityByCategory] @filter={0}, @city={1}, @longitude={2}, @latitude={3}, @start={4}, @limit={5},@category={6},@timecondition={7},@distancecondition={8},@personCountCondition={9}",
                         new object[] { filter, city, longitude, latitude, start, limit, categoryCode, timeCondition, distanceCondition, personCountCondition }).ToList();
                PagedList<Activity> pagedList = new PagedList<Activity>();
                pagedList.Items.AddRange(list);
                pagedList.Start = start;
                pagedList.Limit = limit;
                pagedList.Total = reps.SearchActivityCountByCategory(filter, city, longitude, latitude, categoryCode);

                return new ServiceResult<PagedList<Activity>>(ErrorCode.NoError, pagedList);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="city"></param>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <param name="timeCondition"></param>
        /// <param name="distanceCondition"></param>
        /// <param name="personCountCondition"></param>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public ServiceResult<PagedList<Activity>> SearchActivityList(string filter, string city,
            double longitude, double latitude, int timeCondition, int distanceCondition,
            int personCountCondition,
            int start, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                ActivityRepository reps = new ActivityRepository(dbContext);
                List<Activity> list = dbContext.Database.SqlQuery<Activity>("exec [SP_SearchActivity] @filter={0}, @city={1}, @longitude={2}, @latitude={3}, @start={4}, @limit={5},@timecondition={6},@distancecondition={7},@personCountCondition={8}",
                         new object[] { filter, city, longitude, latitude, start, limit, timeCondition, distanceCondition, personCountCondition }).ToList();
                PagedList<Activity> pagedList = new PagedList<Activity>();
                pagedList.Items.AddRange(list);
                pagedList.Start = start;
                pagedList.Limit = limit;
                pagedList.Total = reps.SearchActivityCount(filter, city, longitude, latitude);

                return new ServiceResult<PagedList<Activity>>(ErrorCode.NoError, pagedList);
            }
        }

        /// <summary>
        /// 更新活动的状态
        /// </summary>
        public void UpdateActivityState()
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                dbContext.Database.ExecuteSqlCommand("exec [SP_UpdateActivityState]");
            }
        }
    }
}
